package com.pet.controller;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/chat/{userId}")
public class WebSocketController{
    Map<String, Session> sessions=new ConcurrentHashMap<>();
    private String userId;
    @OnOpen
    public void open(Session session, @PathParam("userId") String userId){
        sessions.put(userId,session);
        this.userId=userId;
        System.out.println(userId+"连接了服务器");
    }
    @OnMessage
    public void onMessage(String message) {
        System.out.println("收到消息"+message);
        try {
            sessions.get(userId).getBasicRemote().sendText("emmmm");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @OnClose
    public void onClose() {
        sessions.remove(userId);
        System.out.println(userId+"断开连接");
    }
    @OnError
    public void onError(Throwable throwable) {
        sessions.remove(userId);
        System.out.println("用户："+userId+"断开连接");
        System.out.println(throwable);
    }

}
